<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SQL编辑器与参数解析系统</title>
    <script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.34.1/min/vs/loader.js"></script>
    <style>
        :root {
            --primary: #3498db;
            --secondary: #2c3e50;
            --success: #2ecc71;
            --warning: #f1c40f;
            --danger: #e74c3c;
            --light: #ecf0f1;
            --dark: #34495e;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: #1e293b;
            color: #f0f9ff;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            background: linear-gradient(135deg, #2c3e50, #1a2530);
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
        }
        
        .header-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .header-title h1 {
            font-size: 28px;
            background: linear-gradient(90deg, #3498db, #2ecc71);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }
        
        .connection-panel {
            background: rgba(44, 62, 80, 0.7);
            padding: 15px;
            border-radius: 8px;
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .connection-input {
            flex: 1;
            min-width: 200px;
        }
        
        .connection-input label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
            color: #bdc3c7;
        }
        
        .connection-input input, select {
            width: 100%;
            padding: 10px;
            background: #2c3e50;
            border: 1px solid #3498db;
            border-radius: 4px;
            color: white;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: var(--primary);
            color: white;
        }
        
        .btn-success {
            background: var(--success);
            color: white;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        
        .main-content {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .editor-section {
            flex: 3;
            background: linear-gradient(135deg, #2c3e50, #1a2530);
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
        }
        
        .section-header {
            padding: 15px 20px;
            background: rgba(0, 0, 0, 0.2);
            border-bottom: 1px solid rgba(52, 152, 219, 0.3);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .section-header h2 {
            font-size: 20px;
            color: #3498db;
        }
        
        .editor-container {
            height: 400px;
            padding: 15px;
        }
        
        .params-section {
            flex: 2;
            background: linear-gradient(135deg, #2c3e50, #1a2530);
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
        }
        
        .params-container {
            padding: 20px;
            max-height: 400px;
            overflow-y: auto;
        }
        
        .params-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .params-table th {
            background: rgba(52, 152, 219, 0.2);
            padding: 12px 15px;
            text-align: left;
            font-weight: 600;
            color: #3498db;
            border-bottom: 1px solid rgba(52, 152, 219, 0.3);
        }
        
        .params-table td {
            padding: 12px 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .params-table tr:last-child td {
            border-bottom: none;
        }
        
        .params-table select {
            width: 100%;
            padding: 8px;
            background: #2c3e50;
            border: 1px solid #3498db;
            border-radius: 4px;
            color: white;
        }
        
        .result-section {
            background: linear-gradient(135deg, #2c3e50, #1a2530);
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
            margin-bottom: 20px;
        }
        
        .result-container {
            padding: 20px;
            min-height: 150px;
            max-height: 300px;
            overflow-y: auto;
            font-family: monospace;
            white-space: pre-wrap;
            background: rgba(0, 0, 0, 0.1);
            border-radius: 0 0 10px 10px;
        }
        
        .example-queries {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 15px;
        }
        
        .example-query {
            background: rgba(52, 152, 219, 0.2);
            border: 1px dashed #3498db;
            border-radius: 4px;
            padding: 8px 12px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .example-query:hover {
            background: rgba(52, 152, 219, 0.4);
        }
        
        .action-buttons {
            display: flex;
            gap: 15px;
            margin-top: 20px;
            justify-content: center;
        }
        
        .btn-large {
            padding: 12px 30px;
            font-size: 16px;
        }
        
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status-connected {
            background-color: var(--success);
            box-shadow: 0 0 8px var(--success);
        }
        
        .status-disconnected {
            background-color: var(--danger);
        }
        
        .sql-keyword {
            color: #3498db;
        }
        
        .sql-function {
            color: #e74c3c;
        }
        
        .sql-string {
            color: #2ecc71;
        }
        
        .sql-comment {
            color: #7f8c8d;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div class="header-title">
                <h1>SQL编辑器与参数解析系统</h1>
                <div>
                    <span class="status-indicator status-connected"></span>
                    <span>数据库已连接</span>
                </div>
            </div>
            
            <div class="connection-panel">
                <div class="connection-input">
                    <label>数据库类型</label>
                    <select id="db-type">
                        <option>MySQL</option>
                        <option>PostgreSQL</option>
                        <option>SQL Server</option>
                        <option>Oracle</option>
                        <option>SQLite</option>
                    </select>
                </div>
                <div class="connection-input">
                    <label>主机</label>
                    <input type="text" value="db.example.com" id="db-host">
                </div>
                <div class="connection-input">
                    <label>端口</label>
                    <input type="text" value="3306" id="db-port">
                </div>
                <div class="connection-input">
                    <label>数据库</label>
                    <input type="text" value="company_db" id="db-name">
                </div>
                <div class="connection-input">
                    <label>用户名</label>
                    <input type="text" value="admin" id="db-user">
                </div>
                <div class="connection-input">
                    <label>密码</label>
                    <input type="password" value="password" id="db-pass">
                </div>
                <div class="connection-input" style="align-self: flex-end;">
                    <button class="btn btn-primary" id="test-connection">测试连接</button>
                </div>
            </div>
        </header>
        
        <div class="main-content">
            <div class="editor-section">
                <div class="section-header">
                    <h2>SQL 编辑器</h2>
                    <div>
                        <button class="btn btn-primary" id="parse-btn">解析参数</button>
                    </div>
                </div>
                <div class="editor-container" id="editor"></div>
            </div>
            
            <div class="params-section">
                <div class="section-header">
                    <h2>参数配置</h2>
                    <div>
                        <button class="btn btn-primary" id="validate-btn">验证语法</button>
                    </div>
                </div>
                <div class="params-container">
                    <table class="params-table">
                        <thead>
                            <tr>
                                <th>参数名</th>
                                <th>字段名</th>
                                <th>推断类型</th>
                                <th>覆盖类型</th>
                            </tr>
                        </thead>
                        <tbody id="params-list">
                            <!-- 参数将动态添加到这里 -->
                        </tbody>
                    </table>
                    
                    <div class="help-text">
                        <p><strong>使用说明：</strong></p>
                        <p>在SQL中使用 <span class="sql-keyword">:param</span> 格式定义参数</p>
                        <p>系统会自动解析参数并推断类型</p>
                        <p>您可以在"覆盖类型"列调整参数类型</p>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="result-section">
            <div class="section-header">
                <h2>执行结果</h2>
            </div>
            <div class="result-container" id="result-output">
                <!-- 结果将显示在这里 -->
            </div>
        </div>
        
        <div class="example-queries">
            <div class="example-query" data-query="SELECT * FROM users WHERE age > :min_age AND status = :user_status">
                示例查询 1: 用户筛选
            </div>
            <div class="example-query" data-query="SELECT product_id, name, price FROM products WHERE category = :product_category AND price BETWEEN :min_price AND :max_price">
                示例查询 2: 产品查询
            </div>
            <div class="example-query" data-query="INSERT INTO orders (user_id, product_id, quantity) VALUES (:user_id, :product_id, :qty)">
                示例查询 3: 订单插入
            </div>
        </div>
        
        <div class="action-buttons">
            <button class="btn btn-primary btn-large" id="execute-btn">执行 EXPLAIN 验证</button>
            <button class="btn btn-success btn-large" id="execute-full-btn">执行完整查询</button>
        </div>
    </div>

    <script>
        // 初始化 Monaco Editor
        require.config({ paths: { 'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor@0.34.1/min/vs' }});
        
        let monacoEditor;
        
        require(['vs/editor/editor.main'], function() {
            monacoEditor = monaco.editor.create(document.getElementById('editor'), {
                value: `-- 使用 :param 格式定义参数\nSELECT user_id, username, email\nFROM users\nWHERE \n  department = :dept_name\n  AND join_date > :start_date\n  AND status = :user_status\nORDER BY join_date DESC\nLIMIT :max_results;`,
                language: 'sql',
                theme: 'vs-dark',
                fontSize: 14,
                minimap: { enabled: false },
                automaticLayout: true,
                scrollBeyondLastLine: false,
                renderLineHighlight: 'all',
                lineNumbers: 'on',
                roundedSelection: false,
                scrollbar: {
                    vertical: 'auto',
                    horizontal: 'auto'
                },
                suggest: {
                    showKeywords: true
                }
            });
        });
        
        // 解析SQL参数
        function parseParameters() {
            const sql = monacoEditor.getValue();
            const paramPattern = /:(\w+)/g;
            const params = new Set();
            let match;
            
            // 查找所有参数
            while ((match = paramPattern.exec(sql)) !== null) {
                params.add(match[1]);
            }
            
            // 清空当前参数列表
            const paramsList = document.getElementById('params-list');
            paramsList.innerHTML = '';
            
            // 模拟推断类型
            const typeMapping = {
                'id': 'INT',
                'age': 'INT',
                'price': 'DECIMAL(10,2)',
                'qty': 'INT',
                'status': 'ENUM',
                'date': 'DATE',
                'datetime': 'DATETIME',
                'name': 'VARCHAR(255)',
                'email': 'VARCHAR(100)',
                'category': 'VARCHAR(50)',
                'dept': 'VARCHAR(50)',
                'min': 'INT',
                'max': 'INT',
                'limit': 'INT',
                'offset': 'INT'
            };
            
            // 为每个参数创建行
            params.forEach(param => {
                const row = document.createElement('tr');
                
                // 尝试推断类型
                let inferredType = 'VARCHAR(255)';
                Object.keys(typeMapping).forEach(key => {
                    if (param.toLowerCase().includes(key)) {
                        inferredType = typeMapping[key];
                    }
                });
                
                row.innerHTML = `
                    <td>:${param}</td>
                    <td>${param}</td>
                    <td>${inferredType}</td>
                    <td>
                        <select class="param-type">
                            <option value="VARCHAR(255)" ${inferredType.includes('VARCHAR') ? 'selected' : ''}>VARCHAR</option>
                            <option value="INT" ${inferredType === 'INT' ? 'selected' : ''}>INT</option>
                            <option value="DECIMAL(10,2)" ${inferredType === 'DECIMAL(10,2)' ? 'selected' : ''}>DECIMAL</option>
                            <option value="DATE" ${inferredType === 'DATE' ? 'selected' : ''}>DATE</option>
                            <option value="DATETIME" ${inferredType === 'DATETIME' ? 'selected' : ''}>DATETIME</option>
                            <option value="BOOLEAN" ${inferredType === 'BOOLEAN' ? 'selected' : ''}>BOOLEAN</option>
                            <option value="ENUM" ${inferredType === 'ENUM' ? 'selected' : ''}>ENUM</option>
                        </select>
                    </td>
                `;
                paramsList.appendChild(row);
            });
            
            if (params.size === 0) {
                paramsList.innerHTML = '<tr><td colspan="4" style="text-align: center;">未检测到参数</td></tr>';
            }
            
            // 显示结果
            document.getElementById('result-output').textContent = `成功解析出 ${params.size} 个参数`;
        }
        
        // 验证SQL语法
        function validateSql() {
            const sql = monacoEditor.getValue();
            document.getElementById('result-output').innerHTML = 
                `<span class="sql-keyword">EXPLAIN</span> ${sql}\n\n` +
                `<span class="sql-comment">-- 验证结果 --</span>\n` +
                `✓ SQL语法有效\n` +
                `✓ 表权限验证通过\n` +
                `✓ 参数占位符格式正确`;
        }
        
        // 测试数据库连接
        function testConnection() {
            const dbType = document.getElementById('db-type').value;
            const host = document.getElementById('db-host').value;
            const port = document.getElementById('db-port').value;
            const dbName = document.getElementById('db-name').value;
            
            document.getElementById('result-output').textContent = 
                `正在连接 ${dbType} 数据库：${host}:${port}/${dbName}...\n` +
                `连接成功！服务器版本：${dbType === 'MySQL' ? '8.0.30' : dbType === 'PostgreSQL' ? '14.5' : '15.0'}`;
        }
        
        // 执行完整查询（模拟）
        function executeFullQuery() {
            const sql = monacoEditor.getValue();
            document.getElementById('result-output').innerHTML = 
                `<span class="sql-keyword">EXECUTE</span> ${sql}\n\n` +
                `<span class="sql-comment">-- 执行结果（前10行） --</span>\n` +
                `user_id | username    | email               | status\n` +
                `----------------------------------------------------\n` +
                `1001    | john_doe   | john@example.com    | active\n` +
                `2045    | jane_smith | jane@company.com    | active\n` +
                `3156    | bob_jones  | bob.jones@mail.net  | pending\n` +
                `4223    | alice_wang | alice.w@domain.com  | active\n` +
                `5890    | mike_brown | mike.b@email.org    | inactive\n` +
                `6732    | sarah_lee  | sarah.lee@web.com   | active\n` +
                `7811    | tom_chen   | tomchen@mail.com    | pending\n` +
                `8945    | lisa_kim   | lisa.kim@company.co | active\n` +
                `9078    | dave_wilson| davew@domain.net    | inactive\n` +
                `10234   | amy_nguyen | amyn@email.org      | active`;
        }
        
        // 事件监听
        document.getElementById('parse-btn').addEventListener('click', parseParameters);
        document.getElementById('validate-btn').addEventListener('click', validateSql);
        document.getElementById('test-connection').addEventListener('click', testConnection);
        document.getElementById('execute-btn').addEventListener('click', validateSql);
        document.getElementById('execute-full-btn').addEventListener('click', executeFullQuery);
        
        // 示例查询点击事件
        document.querySelectorAll('.example-query').forEach(element => {
            element.addEventListener('click', function() {
                const query = this.getAttribute('data-query');
                monacoEditor.setValue(query);
                parseParameters();
            });
        });
        
        // 页面加载时解析参数
        window.addEventListener('load', function() {
            // 模拟Monaco加载完成
            setTimeout(parseParameters, 1000);
        });
    </script>
</body>
</html>